package flashcardtest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// make sure we can get special characters
		if (request.getCharacterEncoding() == null)
			request.setCharacterEncoding("UTF-8");
		
		// read data from form
		String newName = request.getParameter("newName");
		String input = request.getParameter("User List");
		String mode = request.getParameter("mode");
		
		System.out.println("newName: " + newName + "   input: " + input + "   mode: " + mode);

		// reset message
		request.getSession().setAttribute("message", "");

		// get reference to user list and current user
		/*
		ArrayList<String> userList = (ArrayList<String>)request.getSession().getAttribute("userlist");
		User localUser = (User)request.getSession().getAttribute("user");
		String currentUserName = "";
		if (localUser != null) {
			currentUserName = localUser.getName();
		}
 	*/

		
		if (mode.equals("Add User")){
			// catch empty name
			if (newName.equals("") ) {
				request.getSession().setAttribute("message", "User name must be filled in.");
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/users.jsp");
				dispatcher.forward(request,response);
				return;
			}
			// determine if user already exists
			/*
			Iterator<String> itr = userList.iterator();
			while (itr.hasNext()) {
				String testname = (String)itr.next();
				if (newName.equals(testname)) {
					// set error message and redirect to user page
					request.getSession().setAttribute("message", "User" + newName + "already exists.");
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/users.jsp");
					dispatcher.forward(request,response);
					return;
				}
			}
			*/
			
			// create new user
			/*
			User newUser = new User(newName);
			userList.add(newName);
			request.getSession().setAttribute("user", newUser);
			*/
			// save user data
			/*
			response.setContentType("text/html");
			String filename = newUser.getFileName();
			ServletContext context = getServletContext();
			String path = context.getRealPath("/data/users/");
			System.out.println("new path:" + path);
			System.out.println("making file:" + path + "/" + filename);
			FileWriter fstream = new FileWriter(path + "/" + filename);
			BufferedWriter out = new BufferedWriter(fstream);
			newUser.save(out);
			out.close();
			*/

		}
		else if (mode.equals("Select User")) {
			// load User
			/*
			User user = new User(input);
			try {
				// load user data from file
				response.setContentType("text/html");
				String filename = "/data/users/" + user.getFileName();
				ServletContext context = getServletContext();
				InputStream inp = context.getResourceAsStream(filename);
				InputStreamReader isr = new InputStreamReader(inp);
				BufferedReader reader = new BufferedReader(isr);
				user.load(reader);
				reader.close();
				isr.close();
			}
			catch (Exception e) {
				System.err.println("ERROR LOADING USER:" + e.getMessage() + " " + e.getClass().getName());
			}
			request.getSession().setAttribute("user", user);
			*/
		}
		else if (mode.equals("Delete User")) {
			/*
			// collect other user names from file
			String deleteUser = input;
			ArrayList<String> users = new ArrayList<String>();
			
			response.setContentType("text/html");
			String filename = "/data/users/users.txt";
			ServletContext context = getServletContext();
			InputStream inp = context.getResourceAsStream(filename);
			if (inp != null) {
				InputStreamReader isr = new InputStreamReader(inp);
				BufferedReader reader = new BufferedReader(isr);
				String title = "";
				// read each entry
				while ((title = reader.readLine()) != null) {
					if (!title.equals(deleteUser)) {
						// add name to list of valid users
						users.add(title);
					}
				}
				reader.close();
			}	
			// write list of still valid users (all but selected user)
			response.setContentType("text/html");
			filename = "/data/users/users.txt";
			context = getServletContext();
			String path = context.getRealPath(filename);
			FileWriter fstream = new FileWriter(path);
			BufferedWriter out = new BufferedWriter(fstream);
			Iterator<String> itr = users.iterator();
			while (itr.hasNext()){
				out.write(itr.next() + "\n");
			}
			out.close();
			
			// remove dictionary from user list registered with Session
	
			itr = userList.iterator();
			while (itr.hasNext()) {
				String testtitle = (String)itr.next();
				if (testtitle.equals(deleteUser)) {
					itr.remove();
				}
			}

			// void currentUser if that user was just deleted
			if (currentUserName.equals(deleteUser)) {
				request.getSession().removeAttribute("user");
			}
			
			// redirect to user page
			getServletContext().getRequestDispatcher("/users.jsp").forward(request, response);
			return;
			*/
		}
		

		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/users.jsp");
		dispatcher.forward(request,response);

	}

}
